'''
    Copyright (C) 2007  Brian Will

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.


Use http://code.google.com/p/pigeon-programming-language/issues/list for contacting the author.
'''

'''
     Externally used: compileModule()
'''

from pigeonParser import parseFile
import sExpressionProcessors as SEP

def compileModule(pigeonFileName):
    '''
    Given pigeon file 'x.pig', write python module called 'x.py' in the same directory
    '''
    
    PREAMBLE = '''
import pigeonOperators
def boolCheck_(expression):
    assert type(expression) == bool, 'A condition expression must evaluate to a boolean value.'
    return expression
'''
    
    syntaxTree = parseFile(pigeonFileName)

    idx = 0
    pythonCode = [PREAMBLE]
    
    code, idx = SEP.processStatementGroup('import', syntaxTree, idx)
    pythonCode.append(code)
    
    code, idx = SEP.processStatementGroup('modvar', syntaxTree, idx)
    pythonCode.append(code)
    
    code, idx = SEP.processStatementGroup('function', syntaxTree, idx)
    pythonCode.append(code)
    
    pythonCode.append('__mainFunc__ = globals().get("main")\n'
        + 'if callable(__mainFunc__): __mainFunc__()\n'
    )
    
    SEP.checkNamespaceCollisions()
    
    pythonCode = ''.join(pythonCode)
    pythonCode = indentCode(pythonCode)
    
    outputFile = open(pigeonFileName[:-3] + 'py', 'w')
    outputFile.write(pythonCode)
    outputFile.close()

def indentCode(code):
    indentedLines = []
    indentLevel = 0
    for line in code.splitlines():
        if line == SEP.BLOCK_START_DELIMITER:
            indentLevel += 1
        elif line == SEP.BLOCK_END_DELIMITER:
            indentLevel -= 1
        else:
            indentedLines.append('\t' * indentLevel + line)
    assert indentLevel == 0, 'INTERNAL ERROR: Indentation level marker imbalance.'    
    return '\n'.join(indentedLines)